package org.rjxh.examfront.web.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.rjxh.examfront.mapper.ExamRoleMapper;
import org.rjxh.examfront.mapper.ExamUserMapper;
import org.rjxh.examfront.pojo.ExamUser;
import org.rjxh.examfront.pojo.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 该类实现了UserDetailsService接口
 * 并重写了其中的loadUserByUsername方法
 * 该方法根据传入的用户名，返回一个UserDetails对象
 * 如果用户名不存在，则抛出UsernameNotFoundException异常
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private ExamUserMapper examUserMapper;
    @Resource
    private ExamRoleMapper examRoleMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<ExamUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ExamUser::getUserName, username);
        ExamUser examUser = examUserMapper.selectOne(wrapper);

        if (Objects.isNull(examUser)){
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        //拿到用户 去数据库查权限
        List<String> authorities = examRoleMapper.selectPermsByUserId(examUser.getUserId());

        return new LoginUser(examUser,authorities);
    }
}
